﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Castle.Core.Resource;
using MailKit.Search;
using MySqlX.XDevAPI.Common;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using Microsoft.VisualBasic;
using Org.BouncyCastle.Asn1.X509;
using System.Threading;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    ///  ATS_客户档案创建
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CRMtoATSCustomerCreateController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_zh;
        public readonly string con_qh;
        public readonly string con_yb;
        public readonly string con_oa;


        public CRMtoATSCustomerCreateController(ILogger<CRMtoATSCustomerCreateRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_yb = _configuration.GetConnectionString("WMSDbConnection_YB");
            con_oa = _configuration.GetConnectionString("OA_DbConnection");
            _logger = loggerFactory.CreateLogger<CRMtoATSCustomerCreateController>();
        }

        /// <summary>
        /// ATS_客户档案创建
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostATSCustomerCreate([FromBody] CRMtoATSCustomerCreateRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            CRMPriceReportResponseDto re = new CRMPriceReportResponseDto();

            try
            {

                string sql_str = "select khbh,khmc,'221'zzid from xdap_app_339816917906751489.crm_khda where  khzt='[\"zc\"]' and khbh='"+strparm.custome_code+"' ";
                DataTable dt = DB.Query(sql_str,con);
                if (dt.Rows.Count>0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        Thread.Sleep(1000);
                        Mbs input = new Mbs();

                        Pub intput_pub = new Pub();

                        intput_pub.srcbatchno = "ZJCRM" + DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
                        intput_pub.checktext = "";
                        intput_pub.timezone = "GMT+8";
                        intput_pub.transcode = "CMSQ01";
                        intput_pub.transdatetime = DateTime.Now.ToString();
                        intput_pub.srcoutsystemcode = "CRM1";
                        intput_pub.version = "3";
                        intput_pub.licensecode = "GJTYNCRM1";

                        Req intput_req = new Req();


                        List intput_List = new List();
                        Accounts intput_Accounts = new Accounts();

                        List<Accountdetail> intput_Accountdetail = new List<Accountdetail>();

                        intput_Accountdetail.Add(new Accountdetail {
                            agentswiftcode = "",
                            accountnumber = "",
                            privateflag = "",
                            residentcountrycode = "",
                            isactive = "",
                            description = "",
                            currencycode = "",
                            areacode = "",
                            agentbankcode = "",
                            banklocations = "",
                            accountname = "",
                            residenttype = "",
                            certtype = "",
                            certnumber = "",
                            agentaccountnumber = "",
                            cellphone = "",
                            isdefaultsettlementaccount = "",
                            eledrafits = "",
                            cardtype = "",
                            agentbanklocations = "",
                            bankcode = "",
                            agentareacode = "",
                            regorgcode = "",
                            cnaps = ""
                        } );

                        intput_Accounts.accountdetail = intput_Accountdetail;

                        List<Detail> intput_Detail = new List<Detail>();

                        intput_Detail.Add(new Detail
                        {
                            code= row["khbh"].ToString(),
                            address="",
                            categorycode= "ZJCRM",
                            orgcode="221",
                            isactive="1",
                            description="",
                            reconciliationaccount="",
                            urid="",
                            includesubs="1",
                            name = row["khmc"].ToString(),
                            accounts= intput_Accounts,
                            srcoutsystemcode= "CRM1",
                            email=""

                        });

                        intput_List.detail = intput_Detail;
                        intput_req.list = intput_List;

                        input.pub = intput_pub;
                        input.req = intput_req;

                        ATS_REQ ATS_IN = new ATS_REQ();
                        ATS_IN.mbs = input;


                        Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                        urldic.Add("function_description", "ATS客户档案创建");//查看URL配置表地址描述
                        DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址

                        string jsonText = JsonConvert.SerializeObject(ATS_IN);

                        DateTime requestid_t = DateTime.Now;

                        var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");

                        string result_ = JsonConvert.SerializeObject(reAgv);

                        //日志记录
                        dic = new Dictionary<string, string>(); //获取
                        dic.Add("Url", url_dt.Rows[0]["interface_url"].ToString());
                        dic.Add("request", jsonText);
                        dic.Add("result", result_);
                        dic.Add("request_time", requestid_t.ToString());
                        MethodHelp.log_create(dic, con);

                        if (reAgv.ToString().Contains("E00001"))
                        {
                            strMsg = reAgv.ToString();
                        }

                    }
                }
                else
                {
                    strMsg = "获取不到客户编码=<"+strparm.custome_code+">数据记录！";
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            //_logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
